<template>
  <view class="profile-page">
    <!-- 1. 顶部区域 - 简洁现代风格 -->
    <view class="profile-header">
      <!-- 背景图片区域 -->
      <view class="header-bg">
        <image src="/static/images/sanyueqi.png" mode="aspectFill" alt="背景图"></image>
      </view>
    </view>

    <!-- 2. 用户信息区（现代简约风格） -->
    <view class="user-card">
      <!-- 头像区域 - 简化设计 -->
      <view class="avatar-container">
        <image 
          class="user-avatar" 
          :src="userInfo.avatar" 
          mode="aspectFill"
        ></image>
        <!-- 认证标识 -->
        <view class="verified-badge">
          <uni-icons type="checkmark-circle" size="16" color="#4cd964"></uni-icons>
        </view>
      </view>

      <!-- 用户名区域 - 居中对齐 -->
      <view class="user-name-container">
        <text class="user-name">{{ userInfo.username }}</text>
      </view>

      <!-- 个性签名 -->
      <text class="user-signature">{{ userInfo.signature }}</text>

      <!-- 数据统计 -->
      <view class="user-stats">
        <view class="stat-item" @click="viewMyRecipes">
          <text class="stat-num">{{ userInfo.recipeCount }}</text>
          <text class="stat-name">我的菜谱</text>
        </view>
        <view class="stat-item" @click="viewLikes">
          <text class="stat-num">{{ userInfo.likeCount }}</text>
          <text class="stat-name">点赞</text>
        </view>
        <view class="stat-item" @click="viewCollections">
          <text class="stat-num">{{ userInfo.collectionCount }}</text>
          <text class="stat-name">收藏</text>
        </view>
        <view class="stat-item" @click="viewFollowers">
          <text class="stat-num">{{ userInfo.followerCount }}</text>
          <text class="stat-name">粉丝</text>
        </view>
        <view class="stat-item" @click="viewFollowing">
          <text class="stat-num">{{ userInfo.followingCount }}</text>
          <text class="stat-name">关注</text>
        </view>
      </view>
    </view>

    <!-- 3. 功能菜单区 -->
    <view class="function-list">
      <!-- 第一组菜单：核心功能 -->
      <view class="menu-group">
        <view class="menu-item" @click="viewMyRecipes">
          <uni-icons class="menu-icon" type="list" size="18" color="#ff6b6b"></uni-icons>
          <text class="menu-text">我的菜谱</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>
        <view class="menu-item" @click="viewCollections">
          <uni-icons class="menu-icon" type="star" size="18" color="#ffc107"></uni-icons>
          <text class="menu-text">我的收藏</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>
        <view class="menu-item" @click="viewAIChat">
          <uni-icons class="menu-icon" type="chatbubble" size="18" color="#67c23a"></uni-icons>
          <text class="menu-text">AI询问</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>
      </view>
      
      <!-- 第二组菜单：辅助功能 -->
      <view class="menu-group">
        <view class="menu-item" @click="viewSettings">
          <uni-icons class="menu-icon" type="settings" size="18" color="#606266"></uni-icons>
          <text class="menu-text">设置</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>
        <view class="menu-item" @click="viewHelp">
          <uni-icons class="menu-icon" type="help" size="18" color="#606266"></uni-icons>
          <text class="menu-text">帮助中心</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>
        <view class="menu-item" @click="contactUs">
          <uni-icons class="menu-icon" type="person" size="18" color="#606266"></uni-icons>
          <text class="menu-text">联系我们</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 5. 退出登录按钮 -->
    <button class="logout-btn" @click="backLogin()">退出登录</button>
    
    <!-- 6. 注销账号按钮 -->
    <button class="delete-account-btn" @click="showDeleteConfirm()">注销账号</button>
  </view>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref, onMounted, watch } from 'vue';
import { getUserFollowers, getUserFollowersByUsername, getUserFollowing, getUserCollectionCount, getUserLikeCount, deleteAccount as deleteAccountAPI, getUserRecipes } from '/apis/index.js';

// 路由实例
const router = useRouter();
const route = useRoute();

// 用户信息数据
const userInfo = ref({
  username: 'XiaoYoe',
  avatar: '/static/images/fuxuan.png',
  signature: '爱生活，爱美食，分享烹饪的快乐',
  recipeCount: 12,
  likeCount: 3, // 新增点赞数
  collectionCount: 36,
  followerCount: 358,
  followingCount: 389
});

// 从本地缓存加载用户信息并获取真实粉丝和关注数量
const loadUserInfo = async () => {
  try {
    const userInfoStr = uni.getStorageSync('userInfo');
    if (userInfoStr) {
      // 解析JSON字符串为对象
      const user = JSON.parse(userInfoStr);
      
      // 更新基本用户信息
      userInfo.value = {
        ...userInfo.value,
        username: user.username || userInfo.value.username,
        email: user.email,
        id: user.id,
        // 如果有真实头像，清理后使用，否则使用默认头像
        avatar: user.avatar ? cleanAvatarUrl(user.avatar) : userInfo.value.avatar
      };
      
      // 如果有用户ID，获取真实的粉丝和关注数量
      if (user.id) {
        await updateUserStats(user.id);
      } else if (user.username) {
        // 如果没有ID但有用户名，使用用户名获取
        await updateUserStatsByUsername(user.username);
      }

    }
  } catch (error) {
    console.log("获取用户粉丝和关注数量失败:", error);
  }
};

// 使用用户ID更新粉丝、关注、收藏和点赞数量
const updateUserStats = async (userId) => {
  try {
    
    // 同时获取粉丝、关注、收藏、点赞数量和用户菜谱
    const [followersResponse, followingResponse, collectionResponse, likeResponse, recipesResponse] = await Promise.all([
      getUserFollowers(userId, 1, 1),
      getUserFollowing(userId, 1, 1),
      getUserCollectionCount(userId),
      getUserLikeCount(userId),
      getUserRecipes()
    ]);
    
    
    
    // 根据request.js的处理逻辑，直接获取返回的数据
    // 注意：request.js会根据响应格式返回不同的数据结构
    let totalFollowers = 0;
    let totalFollowing = 0;
    
    // 处理粉丝响应 - 检查不同可能的响应格式
    if (followersResponse && typeof followersResponse === 'object') {
      // 格式1: {total: number}
      if ('total' in followersResponse) {
        totalFollowers = followersResponse.total || 0;
      }
      // 格式2: {data: {total: number}}
      else if (followersResponse.data && 'total' in followersResponse.data) {
        totalFollowers = followersResponse.data.total || 0;
      }
      // 格式3: 数组直接包含数据
      else if (Array.isArray(followersResponse)) {
        totalFollowers = followersResponse.length;
      }
    }
    
    // 处理关注响应 - 检查不同可能的响应格式
    if (followingResponse && typeof followingResponse === 'object') {
      // 格式1: {total: number}
      if ('total' in followingResponse) {
        totalFollowing = followingResponse.total || 0;
      }
      // 格式2: {data: {total: number}}
      else if (followingResponse.data && 'total' in followingResponse.data) {
        totalFollowing = followingResponse.data.total || 0;
      }
      // 格式3: 数组直接包含数据
      else if (Array.isArray(followingResponse)) {
        totalFollowing = followingResponse.length;
      }
    }
    
    
    
    // 处理收藏响应
    let totalCollections = 0;
    if (collectionResponse && typeof collectionResponse === 'object') {
      if ('total' in collectionResponse) {
        totalCollections = collectionResponse.total || 0;
      } else if (collectionResponse.data && 'total' in collectionResponse.data) {
        totalCollections = collectionResponse.data.total || 0;
      } else if (typeof collectionResponse.count === 'number') {
        totalCollections = collectionResponse.count;
      }
    }

    // 处理点赞响应
    let totalLikes = 0;
    if (likeResponse && typeof likeResponse === 'object') {
      if ('total' in likeResponse) {
        totalLikes = likeResponse.total || 0;
      } else if (likeResponse.data && 'total' in likeResponse.data) {
        totalLikes = likeResponse.data.total || 0;
      } else if (typeof likeResponse.count === 'number') {
        totalLikes = likeResponse.count;
      }
    }
    
    // 处理菜谱响应
    let totalRecipes = 0;
    if (recipesResponse && Array.isArray(recipesResponse)) {
      totalRecipes = recipesResponse.length;
    } else if (recipesResponse && typeof recipesResponse === 'object') {
      if (Array.isArray(recipesResponse.data)) {
        totalRecipes = recipesResponse.data.length;
      } else if (typeof recipesResponse.count === 'number') {
        totalRecipes = recipesResponse.count;
      }
    }

    // 只有当获取到有效数据时才更新，否则保持默认值
    userInfo.value = {
      ...userInfo.value,
      followerCount: totalFollowers >= 0 ? totalFollowers : userInfo.value.followerCount,
      followingCount: totalFollowing >= 0 ? totalFollowing : userInfo.value.followingCount,
      collectionCount: totalCollections >= 0 ? totalCollections : userInfo.value.collectionCount,
      likeCount: totalLikes >= 0 ? totalLikes : userInfo.value.likeCount,
      recipeCount: totalRecipes >= 0 ? totalRecipes : userInfo.value.recipeCount
    };
  } catch (error) {
    
    // 失败时不影响页面显示，继续使用默认值
  }
};

// 使用用户名更新粉丝数量
const updateUserStatsByUsername = async (username) => {
  try {
    
    // 使用用户名获取粉丝数据（只需要第一页，获取总数）
    const followersResponse = await getUserFollowersByUsername(username, 1, 1);
    
    
    
    // 根据request.js的处理逻辑，直接获取返回的数据
    let totalFollowers = 0;
    
    // 处理粉丝响应 - 检查不同可能的响应格式
    if (followersResponse && typeof followersResponse === 'object') {
      // 格式1: {total: number}
      if ('total' in followersResponse) {
        totalFollowers = followersResponse.total || 0;
      }
      // 格式2: {data: {total: number}}
      else if (followersResponse.data && 'total' in followersResponse.data) {
        totalFollowers = followersResponse.data.total || 0;
      }
      // 格式3: 数组直接包含数据
      else if (Array.isArray(followersResponse)) {
        totalFollowers = followersResponse.length;
      }
    }
    
    
    
    // 只有当获取到有效数据时才更新，否则保持默认值
    if (totalFollowers >= 0) {
      userInfo.value = {
        ...userInfo.value,
        followerCount: totalFollowers
      };
       
    }
  } catch (error) {
    
    // 失败时不影响页面显示，继续使用默认值
  }
};

// 清理头像URL中的反引号字符
const cleanAvatarUrl = (url) => {
  if (typeof url === 'string') {
    // 移除字符串两端的反引号字符
    return url.replace(/^`|`$/g, '').trim();
  }
  return url;
};

// 组件挂载时加载用户信息
onMounted(async () => {
  await loadUserInfo();
});

// 监听路由变化，确保每次进入页面都重新加载用户信息
watch(
  () => route.path,
  async () => {
    // 确保是在个人页面时才加载
    if (route.path === '/pages/profile/profile') {
      // 短暂延迟确保缓存操作已完成
      setTimeout(async () => {
        await loadUserInfo();
      }, 100);
    }
  },
  { immediate: true }
);

// 查看AI询问
const viewAIChat = () => {
  router.push('/pages/ai-help/ai-help');
};

// 查看我的菜谱
const viewMyRecipes = () => {
  uni.navigateTo({
    url: '/pages/recipe-collections/recipe-collections?type=collections'
  });
};

// 查看收藏
const viewCollections = () => {
  uni.navigateTo({
    url: '/pages/recipe-collections/recipe-collections?type=collections'
  });
};

// 查看点赞
const viewLikes = () => {
  uni.navigateTo({
    url: '/pages/recipe-collections/recipe-collections?type=likes'
  });
};

// 查看粉丝
const viewFollowers = () => {
  uni.navigateTo({
    url: '/pages/user-relations/user-relations?type=followers'
  });
};

// 查看关注
const viewFollowing = () => {
  uni.navigateTo({
    url: '/pages/user-relations/user-relations?type=following'
  });
};

// 查看设置
const viewSettings = () => {
  router.push('/pages/mine/settings');
};

// 查看帮助中心
const viewHelp = () => {
  router.push('/pages/help/help');
};

// 联系我们
const contactUs = () => {
  router.push('/pages/mine/contact');
};

//退出登录
const backLogin = async() => {
  try {
    // 清空本地用户数据缓存
    uni.removeStorageSync('userInfo');
    // 同时清空token
    uni.removeStorageSync('token');

    
    // 重置用户信息状态
    userInfo.value = {
      username: 'XiaoYoe',
      avatar: '/static/images/fuxuan.png',
      signature: '爱生活，爱美食，分享烹饪的快乐',
      recipeCount: 12,
      likeCount: 0,
      collectionCount: 36,
      followerCount: 258,
      followingCount: 89
    };
    
    // 使用redirectTo确保页面栈中只有登录页
    uni.redirectTo({
      url:`/pages/login/login`
    });
  } catch (error) {

    // 即使出错也跳转到登录页
    uni.redirectTo({
      url:`/pages/login/login`
    });
  }
};

// 显示注销账号确认对话框
const showDeleteConfirm = () => {
  uni.showModal({
    title: '注销账号确认',
    content: '您确定要注销账号吗？此操作将删除您的所有数据，且无法恢复！',
    confirmText: '确认注销',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        // 用户确认注销
        deleteAccount();
      }
    }
  });
};

// 注销账号
const deleteAccount = async () => {
  try {
    // 显示加载中
    uni.showLoading({
      title: '处理中...',
      mask: true
    });
    
    // 调用注销账号API
    const response = await deleteAccountAPI();
    
    // 先隐藏加载中
    uni.hideLoading();
    
    if (response && response.success) {
      // 注销成功，清空本地缓存
      uni.removeStorageSync('userInfo');
      uni.removeStorageSync('token');
      
      // 显示成功提示
      uni.showToast({
        title: '账号已成功注销',
        icon: 'success'
      });
      
      // 跳转到登录页
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/login/login'
        });
      }, 1500);
    } else {
      // 注销失败
      uni.showToast({
        title: response?.message || '账号注销失败',
        icon: 'none'
      });
    }
  } catch (error) {
    // 先隐藏加载中
    uni.hideLoading();
    
    console.error('注销账号失败:', error);
    uni.showToast({
      title: '账号注销失败，请稍后再试',
      icon: 'none'
    });
  }
};
</script>

<style lang="scss" scoped>
/* 全局样式重置与基础变量 */
$primary: #ff6b6b;       // 主色（延续项目风格）
$primary-light: #ff8e8e; // 主色浅色
$primary-dark: #ff5252;  // 主色深色
$gray-light: #f8f8f8;    // 浅灰（背景色）
$gray-medium: #eee;      // 中灰（分割线、边框）
$gray-dark: #666;        // 深灰（辅助文字）
$text-main: #333;        // 主文字色
$radius: 20px;           // 更大圆角，更现代
$shadow: 0 2px 8px rgba(0, 0, 0, 0.06); // 更柔和的阴影
$transition: all 0.3s ease; // 统一样式过渡效果

.profile-page {
  min-height: 100vh;
  background-color: $gray-light;
  padding-bottom: 40px;
}

/* 1. 顶部区域 - 现代简约风格 */
.profile-header {
  width: 100%;
  height: 180px; // 更紧凑的高度
  overflow: hidden;
  position: relative;

  // 背景图片样式
  .header-bg {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    
    image {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
    
    // 添加半透明遮罩层，让背景与内容更好地融合
    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
  }
}

/* 2. 用户信息卡片（现代简约风格） - 部分覆盖在背景图上方 */
.user-card {
  margin-left: 30rpx;
  margin-right: 30rpx;
  margin-top: -80px; /* 负边距，使其部分覆盖在背景图上方 */
  margin-bottom: 20rpx;
  padding: 30rpx 50rpx;
  padding-top: 50px; /* 增加顶部内边距，为头像留出空间 */
  background-color: #fff;
  border-radius: $radius;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); /* 增强阴影效果 */
  position: relative;
  text-align: center;
  z-index: 20; /* 确保在背景图之上 */
  
  // 头像区域 - 优化位置，使其突出显示
  .avatar-container {
    width: 100px;
    height: 100px;
    position: absolute;
    top: -50px;
    left: 50%;
    transform: translateX(-50%);
    // 添加轻微阴影效果
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border-radius: 50%;
    border: 3px solid #fff;
    z-index: 30; /* 确保在卡片之上 */

    .user-avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      object-fit: cover;
    }

    // 认证标识 - 简化设计
    .verified-badge {
      position: absolute;
      bottom: -4px;
      right: -4px;
      width: 28px;
      height: 28px;
      background-color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }

  /* 用户名区域 - 居中对齐 */
  .user-name-container {
    margin-top: 30px; // 调整上边距，适应头像的绝对定位
    margin-bottom: 32rpx;

    .user-name {
      font-size: 45rpx;
      font-weight: 600;
      color: $text-main;
    }
  }

  // 个性签名
  .user-signature {
    font-size: 14px;
    color: $gray-dark;
    line-height: 1.5;
    margin-bottom: 20px;
    display: -webkit-box;
    -webkit-line-clamp: 2; // 最多显示2行
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-align: center;
  }

  // 数据统计
  .user-stats {
    display: flex;
    justify-content: space-around;
    padding-top: 20px;
    border-top: 1px solid $gray-medium;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 10px 0;
      transition: $transition;
      &:active {
        transform: scale(1.05);
      }

      .stat-num {
        font-size: 20px;
        font-weight: 700;
        color: $primary;
        margin-bottom: 4px;
        line-height: 1;
      }

      .stat-name {
        font-size: 13px;
        color: $gray-dark;
      }
    }
  }
}

/* 3. 功能菜单区 - 统一风格 */
.function-list {
  width: calc(100% - 30px);
  margin: 0 auto 25px;

  // 菜单组
  .menu-group {
    background-color: #fff;
    border-radius: $radius;
    box-shadow: $shadow;
    margin-bottom: 15px;
    overflow: hidden;

    // 单个菜单项 - 简化设计
    .menu-item {
      display: flex;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid $gray-medium;
      transition: $transition;

      // 最后一个菜单项清除下边框
      &:last-child {
        border-bottom: none;
      }

      .menu-icon {
        width: 20px;
        text-align: center;
      }

      .menu-text {
        font-size: 15px;
        color: $text-main;
        margin-left: 12px;
        flex: 1;
      }

      // 点击反馈 - 更柔和的效果
      &:active {
        background-color: rgba(255, 107, 107, 0.05);
      }
    }
  }
}

/* 5. 退出登录按钮 - 统一风格 */
.logout-btn {
  width: calc(100% - 30px);
  margin: 0 auto 10px;
  background-color: #fff;
  border: 1px solid $gray-medium;
  color: $gray-dark;
  border-radius: $radius;
  padding: 12px 0;
  font-size: 15px;
  transition: $transition;

  // 清除uniapp默认按钮样式
  &::after {
    border: none;
  }

  // 点击效果
  &:active {
    background-color: $primary;
    border-color: $primary;
    color: #fff;
  }
}

/* 6. 注销账号按钮 - 醒目的警告样式 */
.delete-account-btn {
  width: calc(100% - 30px);
  margin: 0 auto;
  background-color: #fff;
  border: 1px solid $primary;
  color: $primary;
  border-radius: $radius;
  padding: 12px 0;
  font-size: 15px;
  transition: $transition;

  // 清除uniapp默认按钮样式
  &::after {
    border: none;
  }

  // 点击效果
  &:active {
    background-color: $primary;
    color: #fff;
  }
}
</style>